<template>
  <el-card body-style="min-height: 86vh">
    <!-- 搜索 -->
    <el-form :model="searchForm">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="所属区县">
            <el-select v-model="searchForm.areaCode" placeholder="请选择">
              <el-option
                v-for="item in areaList"
                :key="item.areaCode"
                :label="item.area"
                :value="item.areaCode"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="公司名称">
            <el-input v-model="searchForm.name" placeholder="请输入公司名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联系方式">
            <el-input v-model="searchForm.phone" placeholder="请输入联系方式"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item>
            <el-button @click="handleRestSearch">重置</el-button>
            <el-button type="primary" @click="handleGetTableList()">搜索</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <el-divider />
    <!-- 新增、筛选按钮 -->
    <div class="flex justify-between">
      <div class="flex">
        <el-button type="primary" @click="handleDownTemplate">下载模板</el-button>
        <el-upload
          class="ml-2"
          :show-file-list="false"
          accept=".xls,.xlsx"
          :http-request="handleUploadExcel"
        >
          <el-button type="primary" :loading="isLoading">批量导入汽修站</el-button>
        </el-upload>
        <el-tooltip placement="top" class="ml-2">
          <template #content
            >汽修站角色在数据未导入数据库时就已经注册成用户角色<br />汽修站数据之后导入需要修改成汽修站角色</template
          >
          <el-upload
            :show-file-list="false"
            accept=".xls,.xlsx"
            :http-request="handleChangeUserRole"
          >
            <el-button type="primary" class="ml-2" :loading="isRoleLoading">批量修改角色</el-button>
          </el-upload>
        </el-tooltip>
      </div>
      <div>
        <el-button circle @click="handleGetTableList()">
          <template #icon
            ><el-icon> <Refresh /> </el-icon
          ></template>
        </el-button>
      </div>
    </div>
    <!-- 表格 -->
    <el-table :data="tableData">
      <el-table-column prop="area" label="区县" width="80"></el-table-column>
      <el-table-column prop="name" label="公司名称" />
      <el-table-column prop="legalPersonName" label="法人" width="100" />
      <el-table-column prop="phone" label="联系方式" width="120" />
      <el-table-column prop="address" label="地址" />
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button type="primary" @click="handleEditStore(row)">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <el-pagination
      class="flex justify-center mt-2"
      background
      layout="total,prev, pager, next"
      :current-page="currentPage"
      :page-size="limit"
      :total="total"
      @current-change="handleGetTableList"
    />
    <!-- 详情 -->
    <form-drawer ref="formDrawerRef" title="详情" @submit="handleSubmitStore">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="80">
        <el-form-item label="状态">
          <el-switch
            v-model="form.status"
            inline-prompt
            active-text="启用"
            inactive-text="禁用"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </el-form-item>
        <el-form-item label="公司名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
        <el-form-item label="营业执照">
          <el-upload
            :limit="1"
            v-model:file-list="form.businessList"
            list-type="picture-card"
            :http-request="handleUploadBusiness"
            :on-preview="handlePreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
        <el-form-item label="法人">
          <el-input v-model="form.legalPersonName"></el-input>
        </el-form-item>
        <el-form-item label="联系方式">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="地址">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-form-item label="经度">
          <el-input v-model="form.longitude"></el-input>
        </el-form-item>
        <el-form-item label="纬度">
          <el-input v-model="form.latitude"></el-input>
        </el-form-item>
        <el-form-item label="经营范围">
          <el-input v-model="form.businessType"></el-input>
        </el-form-item>
        <el-form-item label="店铺照片">
          <el-upload
            :limit="3"
            v-model:file-list="form.storeList"
            list-type="picture-card"
            :http-request="handleUploadStore"
            :on-preview="handlePreview"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>
      <el-image-viewer
        v-if="showImagePreview"
        :zoom-rate="1.2"
        @close="handleClosePreview"
        :url-list="imgPreviewList"
      />
    </form-drawer>
  </el-card>
</template>
<script setup lang="ts">
import { ref, onMounted } from "vue";
import { useInitTable, useInitForm } from "@/hooks/useCommon";
import useDown from "@/hooks/useDown";
import FormDrawer from "@/components/FormDrawer.vue";
import { toast } from "@/utils/index";
import { getAllRepairStoreList, editRepairStoreApi, importRepairStoreApi,allChangeRoleApi } from "@/api/repair";
import { uploadFileApi, getAreaListApi } from "@/api/user";

// 表格
const { searchForm, tableData, currentPage, limit, total, handleRestSearch, handleGetTableList } =
  useInitTable({
    searchForm: {
      name: "",
      phone: "",
      areaCode: ""
    },
    getTableList: getAllRepairStoreList
  });
// 编辑
let { formDrawerRef, formRef, form, rules, handleEdit, handleSubmit } = useInitForm({
  form: {
    id: "",
    status: 1,
    legalPersonName: "",
    phone: "",
    businessLicense: "",
    businessList: [],
    address: "",
    longitude: "",
    latitude: "",
    storeList: [],
    sitePhotos: "",
    businessType: ""
  },
  updateData: editRepairStoreApi,
  success: () => {
    handleGetTableList();
  }
});
const { downloadUrl } = useDown();
// 下载模板
const handleDownTemplate = () => {
  downloadUrl("https://xct.gzwxxh.com/api/profile/slbg.xlsx", "批量导入");
};
// 批量导入
const isLoading = ref(false);
const handleUploadExcel = async (e: any) => {
  isLoading.value = true;
  try {
    const files = e.file;
    const formData = new FormData();
    formData.append("file", files);
    await importRepairStoreApi(formData);
    toast("上传成功！");
  } finally {
    isLoading.value = false;
  }
};
// 批量修改角色
const isRoleLoading = ref(false)
const handleChangeUserRole = async (e:any) => {
  isRoleLoading.value = true
  try {
    const files = e.file;
    const formData = new FormData();
    formData.append("file", files);
    await allChangeRoleApi(formData);
    toast("修改成功！");
  } finally {
    isRoleLoading.value = false
  }
};
// 编辑
const handleEditStore = (row: any) => {
  const curBus = row.businessLicense
    ? row.businessLicense.split(",").map((item: any) => ({ url: item }))
    : [];
  const curSit = row.sitePhotos
    ? row.sitePhotos.split(",").map((item: any) => ({ url: item }))
    : [];
  const curRow = {
    ...row,
    businessList: curBus,
    storeList: curSit
  };
  handleEdit(curRow);
};

// 上传营业执照
const handleUploadBusiness = async (params: any) => {
  const { file } = params;
  const formData = new FormData();
  formData.append("file", file);
  const res: any = await uploadFileApi(formData);
  form.businessList.pop();
  form.businessList.push({ url: res[0].accessUrl });
};

// 上传店铺照片
const handleUploadStore = async (params: any) => {
  const { file } = params;
  const formData = new FormData();
  formData.append("file", file);
  const res: any = await uploadFileApi(formData);
  form.storeList.pop();
  form.storeList.push({ url: res[0].accessUrl });
};

// 预览
const showImagePreview = ref(false);
const imgPreviewList = ref<any>([]);
const handleClosePreview = () => {
  showImagePreview.value = !showImagePreview.value;
};
const handlePreview = (list: any) => {
  imgPreviewList.value = [list.url];
  showImagePreview.value = !showImagePreview.value;
};

// 保存
const handleSubmitStore = () => {
  form.businessLicense = form.businessList.map((item: any) => item.url).join(",");
  form.sitePhotos = form.storeList.map((item: any) => item.url).join(",");
  handleSubmit();
};

// 获取区县列表
const areaList = ref<any>([]);
const handleGetAreaList = async () => {
  const res: any = await getAreaListApi();
  areaList.value = res;
};

onMounted(() => {
  handleGetAreaList();
});
</script>
<style scoped lang="scss"></style>
